package com.letoy.edu.config.auth;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.letoy.edu.entity.TokenInfo;
import com.letoy.edu.service.ThirdPartService;
import com.letoy.edu.service.auth.AuthUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器
 */
@Component
public class MyThirdPartLoginFilter extends OncePerRequestFilter {

    private AuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
    private AuthenticationFailureHandler failureHandler = new SimpleUrlAuthenticationFailureHandler();
    private AuthenticationManager authenticationManager;


    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
        Assert.notNull(successHandler, "successHandler cannot be null");
        this.successHandler = successHandler;
    }

    public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
        Assert.notNull(failureHandler, "failureHandler cannot be null");
        this.failureHandler = failureHandler;
    }

    protected AuthenticationSuccessHandler getSuccessHandler() {
        return this.successHandler;
    }

    protected AuthenticationFailureHandler getFailureHandler() {
        return this.failureHandler;
    }

    protected AuthenticationManager getAuthenticationManager() {
        return this.authenticationManager;
    }

    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Resource
    ThirdPartService thirdPartService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        if (!"/thirdPart/login".equals(request.getRequestURI())) {
            chain.doFilter(request, response);
        } else {
            ObjectMapper mapper = new ObjectMapper();
            Map<String, String> authenticationBean = null;
            try (InputStream is = request.getInputStream()) {
                authenticationBean = mapper.readValue(is, Map.class);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            System.out.println("当前登录的Token是:" + authenticationBean.get("token"));
            System.out.println("当前登录的类型:" + authenticationBean.get("type"));
            String type = authenticationBean.get("type");
            String token = authenticationBean.get("token");
            String studentNumber = authenticationBean.get("studentNumber");
            TokenInfo tokenInfo = new TokenInfo();
            switch (type) {
                case "facebook":
                    tokenInfo.setFacebook(token);
                    break;
                case "linkedin":
                    tokenInfo.setLinkedin(token);
                    break;
            }

            //通过令牌获取用户名称
            System.out.println(studentNumber);


            AuthUser authUser = thirdPartService.loginByTokenAndType(tokenInfo, type, Integer.parseInt(studentNumber));
            if (authUser != null) {
                String username = authUser.getUsername();
                System.out.println("Token_username = " + username);
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    Map<String, Object> resMap = new HashMap<>();
                    resMap.put("status", 0);
                    resMap.put("token", authUser.getSystemToken());
                    JSONAuthentication.WriteJSONS(request, response, resMap);
                }
            } else {
                Map<String, Object> resMap = new HashMap<>();
                resMap.put("status", 10);
                JSONAuthentication.WriteJSONS(request, response, resMap);
            }


        }

    }
}

